﻿using LayuiMvcUtil.Result;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;

namespace LayuiMvc.WebUI.Permisson
{
    public class ClaimAuthorizeAttribute:AuthorizeAttribute
    {
        public string Claim { get; set; }

        /// <summary>
        /// 判断是否授权的业务
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //获取当前登录用户的声明
            List<string> claimList = new List<string>();
            ClaimsIdentity claimsIdentity = httpContext.User.Identity as ClaimsIdentity;

            if (claimsIdentity!=null)
            {
                claimList = claimsIdentity.Claims.Select(m => m.Value).ToList();
            }

            bool isAuthorize = base.AuthorizeCore(httpContext);
            if (isAuthorize&&!string.IsNullOrEmpty(Claim))
            {
                isAuthorize = claimList.Contains(Claim);
            }
            return isAuthorize;
        }

        /// <summary>
        /// 授权未成功的操作
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var identity = filterContext.HttpContext.User;
            if (!identity.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/Content/page/NoLogin.html");
            }

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new DataResult<string>()
                    {
                        code = 2,
                        msg = "无访问权限"
                    }
                };
            }
            else
            {
                filterContext.Result = new RedirectResult("~/Content/page/NoAuthorize.html");
                return;
            }
        }
    }
}